document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const searchInput = document.getElementById('search-input');
    const searchButton = document.getElementById('search-button');
    const resultsContainer = document.getElementById('results-container');
    const noResultsMessage = document.getElementById('no-results-message');
    const searchStatusMessage = document.getElementById('search-status-message');

    const predictionForm = document.getElementById('prediction-form');
    const stockCodeInput = document.getElementById('stock-code');
    const stockNameInput = document.getElementById('stock-name');
    const predictButton = document.getElementById('predict-button');
    const predictionStatusMessage = document.getElementById('prediction-status-message');
    const predictionContainer = document.getElementById('prediction-container');
    const noPredictionMessage = document.getElementById('no-prediction-message');

    const fundamentalAnalysis = document.getElementById('fundamental-analysis');
    const technicalAnalysis = document.getElementById('technical-analysis');
    const predictionResult = document.getElementById('prediction-result');
    const summaryResult = document.getElementById('summary-result');

    const checkStatusBtn = document.getElementById('check-status-btn');
    const statusContainer = document.getElementById('status-container');

    const flowSteps = document.querySelectorAll('.flow-step');

    // 初始化页面
    checkSystemStatus();

    // 绑定事件监听器
    searchButton.addEventListener('click', performSearch);
    searchInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            performSearch();
        }
    });

    predictionForm.addEventListener('submit', function(e) {
        e.preventDefault();
        performPrediction();
    });

    checkStatusBtn.addEventListener('click', checkSystemStatus);

    // 搜索功能
    async function performSearch() {
        const query = searchInput.value.trim();

        if (!query) {
            showSearchStatus('请输入搜索关键词', 'warning');
            return;
        }

        // 显示搜索状态
        showSearchStatus('正在搜索...', 'info');

        try {
            const response = await fetch(`/api/search?query=${encodeURIComponent(query)}`);
            const data = await response.json();

            if (data.error) {
                showSearchStatus(`搜索出错: ${data.error}`, 'danger');
                return;
            }

            displaySearchResults(data.results);

            // 如果有结果，自动填充预测表单
            if (data.results && data.results.length > 0) {
                // 尝试从搜索结果中提取股票代码和名称
                const titleParts = data.results[0].title.split(' ');
                if (titleParts.length >= 2) {
                    // 假设格式为"股票名称 (股票代码)"
                    const stockName = titleParts[0];
                    const stockCode = titleParts[1].replace(/[()]/g, '');

                    stockNameInput.value = stockName;
                    stockCodeInput.value = stockCode;
                }
            }

            // 隐藏搜索状态
            hideSearchStatus();

            // 激活第一个流程步骤
            activateFlowStep(0);

        } catch (error) {
            showSearchStatus(`搜索请求失败: ${error.message}`, 'danger');
        }
    }

    // 预测功能
    async function performPrediction() {
        const stockCode = stockCodeInput.value.trim();
        const stockName = stockNameInput.value.trim();

        if (!stockCode || !stockName) {
            showPredictionStatus('请输入股票代码和名称', 'warning');
            return;
        }

        // 显示预测状态
        showPredictionStatus('正在搜索股票信息...', 'info');
        disablePredictButton(true);

        // 激活第一个流程步骤 - 搜索股票信息
        activateFlowStep(0);

        try {
            const formData = new FormData();
            formData.append('stock_code', stockCode);
            formData.append('stock_name', stockName);

            // 更新状态为获取股票数据
            setTimeout(() => {
                showPredictionStatus('正在获取股票数据...', 'info');
                activateFlowStep(1);
            }, 2000);

            // 更新状态为AI分析
            setTimeout(() => {
                showPredictionStatus('AI正在分析数据...', 'info');
                activateFlowStep(2);
            }, 3000);

            // 发送预测请求
            const response = await fetch('/api/predict', {
                method: 'POST',
                body: formData
            });

            const data = await response.json();

            if (data.error) {
                showPredictionStatus(`预测失败: ${data.error}`, 'danger');
                disablePredictButton(false);
                return;
            }

            // 更新状态为生成预测
            setTimeout(() => {
                showPredictionStatus('正在生成预测结果...', 'info');
                activateFlowStep(3);
            }, 4000);

            // 显示预测结果
            setTimeout(() => {
                displayPredictionResults(data);
                hidePredictionStatus();
                disablePredictButton(false);
            }, 5000);

        } catch (error) {
            showPredictionStatus(`预测请求失败: ${error.message}`, 'danger');
            disablePredictButton(false);
        }
    }

    // 检查系统状态
    async function checkSystemStatus() {
        statusContainer.innerHTML = `
            <div class="d-flex justify-content-center">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">加载中...</span>
                </div>
            </div>
        `;

        try {
            const response = await fetch('/api/check-status');
            const data = await response.json();

            let statusHTML = '<div class="status-items">';

            // 系统状态
            statusHTML += createStatusItem(
                data.system_ready,
                '系统状态',
                '系统已准备就绪',
                '系统未准备就绪，请检查API密钥和网络连接'
            );

            // 搜索引擎状态
            if ('search_engine_ready' in data) {
                statusHTML += createStatusItem(
                    data.search_engine_ready,
                    '搜索引擎',
                    '搜索引擎已准备就绪',
                    '搜索引擎未准备就绪'
                );
            }

            // 数据获取器状态
            if ('data_fetcher_ready' in data) {
                statusHTML += createStatusItem(
                    data.data_fetcher_ready,
                    '数据获取器',
                    '数据获取器已准备就绪',
                    '数据获取器未准备就绪'
                );
            }

            // DeepSeek API状态
            if ('deepseek_api_ready' in data) {
                statusHTML += createStatusItem(
                    data.deepseek_api_ready,
                    'DeepSeek API',
                    'DeepSeek API已准备就绪',
                    'DeepSeek API未准备就绪'
                );
            }

            // API密钥状态
            if ('anspire_api_configured' in data) {
                statusHTML += createStatusItem(
                    data.anspire_api_configured,
                    'Anspire API密钥',
                    'Anspire API密钥已配置',
                    'Anspire API密钥未配置'
                );
            }

            if ('deepseek_api_configured' in data) {
                statusHTML += createStatusItem(
                    data.deepseek_api_configured,
                    'DeepSeek API密钥',
                    'DeepSeek API密钥已配置',
                    'DeepSeek API密钥未配置'
                );
            }

            statusHTML += '</div>';
            statusContainer.innerHTML = statusHTML;

        } catch (error) {
            statusContainer.innerHTML = `
                <div class="alert alert-danger">
                    检查系统状态失败: ${error.message}
                </div>
            `;
        }
    }

    // 辅助函数：创建状态项
    function createStatusItem(isReady, label, readyText, notReadyText) {
        const statusClass = isReady ? 'status-ready' : 'status-not-ready';
        const iconClass = isReady ? 'fa-check-circle' : 'fa-exclamation-circle';
        const statusText = isReady ? readyText : notReadyText;
        const statusColor = isReady ? '#28a745' : '#dc3545';

        return `
            <div class="status-item ${statusClass}">
                <span class="status-icon">
                    <i class="fas ${iconClass}"></i>
                </span>
                <span class="status-text">
                    <strong>${label}</strong>
                    ${statusText}
                </span>
            </div>
        `;
    }

    // 辅助函数：显示搜索状态
    function showSearchStatus(message, type) {
        searchStatusMessage.textContent = message;
        searchStatusMessage.className = `alert alert-${type}`;
        searchStatusMessage.classList.remove('d-none');
    }

    // 辅助函数：隐藏搜索状态
    function hideSearchStatus() {
        searchStatusMessage.classList.add('d-none');
    }

    // 辅助函数：显示预测状态
    function showPredictionStatus(message, type) {
        predictionStatusMessage.textContent = message;
        predictionStatusMessage.className = `alert alert-${type}`;
        predictionStatusMessage.classList.remove('d-none');
    }

    // 辅助函数：隐藏预测状态
    function hidePredictionStatus() {
        predictionStatusMessage.classList.add('d-none');
    }

    // 辅助函数：禁用/启用预测按钮
    function disablePredictButton(disabled) {
        predictButton.disabled = disabled;
        if (disabled) {
            predictButton.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 预测中...';
        } else {
            predictButton.innerHTML = '<i class="fas fa-chart-line"></i> 开始预测';
        }
    }

    // 辅助函数：显示搜索结果
    function displaySearchResults(results) {
        if (!results || results.length === 0) {
            resultsContainer.innerHTML = '<p class="text-muted">没有找到相关结果</p>';
            noResultsMessage.style.display = 'block';
            return;
        }

        noResultsMessage.style.display = 'none';

        let resultsHTML = '';
        results.forEach(result => {
            // 检查是否有URL，如果有则创建可点击的链接
            const titleElement = result.url ? 
                `<h5 class="result-title"><a href="${result.url}" target="_blank" class="result-link">${result.title || '未知标题'} <i class="fas fa-external-link-alt"></i></a></h5>` : 
                `<h5 class="result-title">${result.title || '未知标题'}</h5>`;
                
            resultsHTML += `
                <div class="result-item">
                    ${titleElement}
                    <p class="result-description">${result.description || result.content || '无描述'}</p>
                    <div class="result-meta">
                        <span>${result.source || '未知来源'}</span>
                        <span>${result.date || result.time || ''}</span>
                    </div>
                </div>
            `;
        });

        resultsContainer.innerHTML = resultsHTML;
    }

    // 辅助函数：显示预测结果
    function displayPredictionResults(data) {
        if (!data) {
            return;
        }

        // 显示预测结果容器
        predictionContainer.classList.remove('d-none');
        noPredictionMessage.style.display = 'none';

        // 格式化并显示基本面分析
        if (data.fundamental_analysis) {
            fundamentalAnalysis.textContent = typeof data.fundamental_analysis === 'string'
                ? data.fundamental_analysis
                : JSON.stringify(data.fundamental_analysis, null, 2);
        } else {
            fundamentalAnalysis.textContent = '无基本面分析数据';
        }

        // 格式化并显示技术面分析
        if (data.technical_analysis) {
            technicalAnalysis.textContent = typeof data.technical_analysis === 'string'
                ? data.technical_analysis
                : JSON.stringify(data.technical_analysis, null, 2);
        } else {
            technicalAnalysis.textContent = '无技术面分析数据';
        }

        // 格式化并显示预测结果
        if (data.final_prediction) {
            predictionResult.textContent = typeof data.final_prediction === 'string'
                ? data.final_prediction
                : JSON.stringify(data.final_prediction, null, 2);
        } else {
            predictionResult.textContent = '无预测结果数据';
        }

        // 格式化并显示结果摘要
        if (data.summary) {
            // 创建更友好的HTML格式展示摘要
            let summaryHTML = '<div class="summary-content">';
            
            // 股票基本信息
            summaryHTML += `
                <div class="summary-section">
                    <h6><i class="fas fa-info-circle"></i> 股票信息</h6>
                    <p>名称: ${data.summary.stock_info.name}</p>
                    <p>代码: ${data.summary.stock_info.code}</p>
                </div>
            `;

            // 基本面分析
            summaryHTML += `
                <div class="summary-section">
                    <h6><i class="fas fa-chart-line"></i> 基本面分析</h6>
                    <p><strong>评级:</strong> ${data.summary.fundamental.rating}</p>
                    <p><strong>结论:</strong> ${data.summary.fundamental.conclusion}</p>
                </div>
            `;

            // 技术面分析
            summaryHTML += `
                <div class="summary-section">
                    <h6><i class="fas fa-chart-bar"></i> 技术面分析</h6>
                    <p><strong>评级:</strong> ${data.summary.technical.rating}</p>
                    <p><strong>结论:</strong> ${data.summary.technical.conclusion}</p>
                </div>
            `;

            // 综合预测
            summaryHTML += `
                <div class="summary-section">
                    <h6><i class="fas fa-lightbulb"></i> 综合预测</h6>
                    <p><strong>综合评级:</strong> ${data.summary.prediction.overall_rating}</p>
                    <p><strong>明日预测:</strong> ${data.summary.prediction.tomorrow_forecast.direction} 
                    (置信度: ${data.summary.prediction.tomorrow_forecast.confidence})</p>
                    <p><strong>投资建议:</strong> ${typeof data.summary.prediction.investment_advice === 'object' ? 
                        JSON.stringify(data.summary.prediction.investment_advice) : 
                        data.summary.prediction.investment_advice}</p>
                    <p><strong>风险提示:</strong> ${data.summary.prediction.risk_warning}</p>
                </div>
            `;

            // 生成时间
            summaryHTML += `
                <div class="text-muted small mt-3">
                    报告生成时间: ${data.summary.generated_at}
                </div>
            `;
            
            // 免责声明
            summaryHTML += `
                <div class="disclaimer alert alert-warning mt-3">
                    <p><i class="fas fa-exclamation-triangle"></i> <strong>免责声明</strong></p>
                    <p>市场有风险，投资需谨慎</p>
                    <p>本分析仅供参考，不构成投资建议</p>
                </div>
            `;

            summaryHTML += '</div>';
            summaryResult.innerHTML = summaryHTML;
        } else {
            summaryResult.innerHTML = '<p class="text-muted">无结果摘要数据</p>';
        }
    }

    // 辅助函数：激活流程步骤
    function activateFlowStep(stepIndex) {
        flowSteps.forEach((step, index) => {
            if (index === stepIndex) {
                step.classList.add('active');
            } else {
                step.classList.remove('active');
            }
        });
    }
});
